package com.zhixing.utils;

import com.zhixing.common.IConstants;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.URLEncoder;

import static com.zhixing.common.IConstants.SYMBOL_UTF_8;

/**
 * 文件下载工具
 * @author zhixing
 */
public class FileDownloadUtil {


    /**
     * 内容下载
     * @param templateContent 模板内容（填充完数据）
     * @param response 响应
     * @param fileName 文件名称
     */
    public static void  writeToResponse(String templateContent, HttpServletResponse response, String fileName) {
        response.setContentType(StrUtils.contractStr(MediaType.APPLICATION_OCTET_STREAM_VALUE,";charset=utf-8"));
        try (BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
            response.setHeader("Content-disposition",
                    StrUtils.contractStr( "attachment;filename=",
                            URLEncoder.encode(StrUtils.contractStr(fileName, IConstants.FILE_SUFFIX.DOC), SYMBOL_UTF_8)));
            byte[] bytes = templateContent.getBytes();
            bos.write(bytes, 0, bytes.length);
            bos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
